import { createRouter, createWebHistory } from 'vue-router'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/',
      name: 'Login',
      component: () => import ('../views/Login/index.vue'),
      meta:{
        requireAuth:false,
        title:'登录'
      }
    },
    {
      path:'/:pathMatch(.*)',
      redirect: '/404',
      children:[
        {
          path: '/404',
          name: '404',
          component: () => import ('../views/Error/404.vue'),
        }
      ]
    },
    {
      path: '/main',
      name: 'Main',
      component: () => import('../views/Layout/index.vue'),
      redirect: '/',
      meta:{
        requireAuth:true,
      },
      children:[
        {
          path: '',
          name: 'Home',
          component: () => import('../views/Layout/Home/index.vue'),
          meta:{
            requireAuth:true,
            title:'数据看板'
          }
        },
        {
          path: 'user',
          name: 'User',
          component: () => import('../views/Layout/User/index.vue'),
          meta:{
            requireAuth:true,
            title:'用户管理'
          }
        },
        {
          path: 'setting',
          name: 'Setting',
          component: () => import('../views/Layout/Setting/index.vue'),
          meta:{
            requireAuth:true,
            title:'网站设置'
          }
        },
        {
          path: 'goods',
          name: 'Goods',
          component: () => import('../views/Layout/Goods/index.vue'),
          meta:{
            requireAuth:true,
            title:'商品管理'
          }
        },
        {
          path: 'orders',
          name: 'Orders',
          component: () => import('../views/Layout/Orders/index.vue'),
          meta:{
            requireAuth:true,
            title:'订单管理'
          }
        },
        {
          path: 'category',
          name: 'Category',
          component: () => import('../views/Layout/Category/index.vue'),
          meta:{
            requireAuth:true,
            title:'分类管理'
          }
        }
      ]
    }
  ]
})

router.beforeEach((to, from, next) => {
  if(to.meta.requireAuth && !sessionStorage.getItem('token')){
    next('/')
    ElMessage.error('请先登录')
  }else{
    next()
  }
})

export default router
